#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

//采购电脑的总金额的统计：无论是创建一个电脑、赋值、复制，始终
//能够显示最新的电脑金额
class Computer{
public:
    Computer(const char * brand, float price)
    :_brand(new char[strlen(brand) + 1]())
    ,_price(price)
    {
        strcpy(_brand, brand);
        _totalPrice += _price;
    }
    ~Computer(){
        if(_brand){
            delete [] _brand;
            _brand = nullptr;
        }
    }
    Computer(const Computer & rhs)
    :_brand(new char[strlen(rhs._brand) + 1]())
    ,_price(rhs._price)
    {
        strcpy(_brand, rhs._brand);
        _totalPrice += _price;
    }
    //思路：
    //1.编译器有提供默认的版本，也就是浅拷贝
    //2.画出浅拷贝对应的内存图示中存在的问题
    //3.根据内存图示，总结出正确的步骤
    //a = b;先减去原来的金额，再加上现有的金额
    Computer & operator=(const Computer & rhs){
        if(this != &rhs){
            //自赋值
            //回收左操作数申请的堆空间
            delete [] _brand;
            _totalPrice -= _price;
            //执行深拷贝
            _brand = new char[strlen(rhs._brand) + 1]();
            strcpy(_brand, rhs._brand);
            _price = rhs._price;
            _totalPrice += _price;
        }

        return *this;
    }

    static float getTotalPrice(){
        return _totalPrice;
    }

private:
    static float _totalPrice;
    char * _brand;
    float _price;
};
float Computer::_totalPrice = 0;


void test(){
    cout << Computer::getTotalPrice() << endl;
    Computer c1("apple", 7800);
    cout << Computer::getTotalPrice() << endl;
    Computer c2 = c1;
    cout << Computer::getTotalPrice() << endl;
    Computer c3("huawei", 5600);
    cout << Computer::getTotalPrice() << endl;
    c3 = c1;
    cout << Computer::getTotalPrice() << endl;
}

int main()
{
    test();
    return 0;
}


